#include "cmd2shell.h"
#include "parser.h"
#include "comm.h"

int main(void)
{
    char input[4][ARGV_LEN] = {0};
    char buf[BUF_LENGTH] = {0};
    char output[OUTPUT_LENGTH] = {0};
    bool sigexit = true;
    int size = 0;

    int msgid = createMsgQueue();
    createFIFOPipe();

    if(callExecutor() == -1)
    {
        perror("callExecutor");
        return -1;
    }

    do
    {
        size = getInput(input, 4);
        sigexit = parser(input, buf, 4);
        sendMsgQueue(msgid, buf);
        readFIFOPipe(output, sizeof(output));
        display(output, sizeof(output));
    }while(sigexit);

    destoryMsgQueue(msgid);

    return 0;
}

int callExecutor()
{
    pid_t backprog;
    backprog = fork();

    if(backprog == 0)
    {
        if(execl("executor", "", NULL) < 0)
        {
            perror("execl");
            return -1;
        }
    }

    else if(backprog > 0)
    {
        sleep(1); // Waiting for executor
    }

    else
    {
        perror("fork");
        return -1;
    }

    return 0;
}

int getInput(char input[][ARGV_LEN], int size)
{
    printf("#cmd2shell#>");
    int i = 0;
    for(i; i < size; i++)
    {
        memset(input[i], 0, ARGV_LEN);
    }
    for(i = 0; i < size; i++)
    {
        scanf("%63s", input[i]);
        if(getchar() == '\n')
            break;
    }
    return i++;
}

int display(char output[], int size) // It can be improved
{
    printf("%s", output);
    return 0;
}
